package cn.com.zetatech.loader.common.ftp;

import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import java.time.Duration;

public class ConnectionClientPool {

    private final GenericObjectPool<ConnectionClient> internalPool;

    public ConnectionClientPool(GenericObjectPoolConfig<ConnectionClient> poolConfig, String serverIP, int serverPort, String userName, String password, String type) {
        if (poolConfig == null) {
            poolConfig = new GenericObjectPoolConfig<>();
            poolConfig.setMaxTotal(3);
            poolConfig.setMinIdle(1);
            poolConfig.setMaxWait(Duration.ofMillis(10000));
            poolConfig.setMinEvictableIdleTime(Duration.ofMinutes(5));
            poolConfig.setTimeBetweenEvictionRuns(Duration.ofMinutes(1));
        }

        AbandonedConfig abandonedConfig = new AbandonedConfig();
        abandonedConfig.setRemoveAbandonedOnMaintenance(true);
        abandonedConfig.setRemoveAbandonedOnBorrow(true);
        abandonedConfig.setRemoveAbandonedTimeout(Duration.ofSeconds(10));
        abandonedConfig.setLogAbandoned(true);

        ConnectionClientFactory factory = new ConnectionClientFactory(serverIP, serverPort, userName, password, type);
        this.internalPool = new GenericObjectPool<>(factory, poolConfig);


        this.internalPool.setAbandonedConfig(abandonedConfig);
    }

    public ConnectionClient borrowObject() throws Exception {
        return internalPool.borrowObject();
    }

    public void returnObject(ConnectionClient channelSftp) {
        try {
            internalPool.returnObject(channelSftp);
        } catch (Exception e) {
            //ignore
        }
    }

    public void close() {
        internalPool.close();
    }


}
